<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Two</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<a href="/" >返回首页</a>
<div id="app">
    <ul>
        <li v-for="bookType in bookTypeList">
            <a ><input type="text" :value="bookType.name" disabled :id="[bookType.id+'updateInput']"></a>

            <button @click.prevent="deleteType(bookType.id)">删除</button>
            <button @click.prevent="updateType(bookType.id)" :id="[bookType.id+'updateBtn']">修改</button>
        </li>
    </ul>
    <button @click.prevent="newTypeView">新增类型</button>
    <input type="text" v-model="newTypeName" v-if="showIt">
    <button v-if="showIt" @click.prevent="newType">确认</button>
</div>
</body>
<script>
    let app = new Vue({
        el: "#app",
        data: {
            bookTypeList: [],
            showIt: false,
            newTypeName: ''
        },
        methods: {
            initBookTypeList() {
                $.get("/booktype/getList", data => {
                    this.bookTypeList = data;
                })
            },
            deleteType(id) {
                $.post("/booktype/deleteById", {id: id}, data => {
                    alert(data);
                    this.initBookTypeList();
                })
            },
            updateType(id) {
                let $updateInput = $('#'+id+'updateInput');
                $updateInput.prop("disabled",false);
                let $updateBtn = $('#'+id+'updateBtn');
                $updateBtn.text("确认");
                let _this = this;
                $updateBtn.click(function () {
                    let updatedName = $updateInput.val();
                    $.post("/booktype/updateById", {id: id, name:updatedName}, data => {
                        _this.initBookTypeList();
                        $updateInput.prop("disabled",true);
                        $updateBtn.text("修改");
                        $updateBtn.unbind();
                    })
                });
            },
            newTypeView(){
                this.showIt = true;
            },
            newType(){
              $.post("/booktype/newType", {name:this.newTypeName}, data => {
                  alert(data);
                  this.initBookTypeList();
                  this.showIt = false;
              })
            }
        },
        created() {
            this.initBookTypeList();
        }
    });

</script>
</html>